package mspdt.ubzuuch.mn;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ExpandableListView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;

public class UBActivity extends Activity{

	private ExpandableListView expList_ub;
	private ArrayList<String> parent_datas = new ArrayList<String>();
	  private ArrayList<ArrayList<String>> child_datas = new ArrayList<ArrayList<String>>();
	  private ArrayList<ArrayList<Integer>> child_ids = new ArrayList<ArrayList<Integer>>();
	  private MainExpandableAdapter main_adapter;
	  private String[] ub_parents = {"Авто машин, сэлбэг", "АТМ", "Байгууллага", "Банк", "Дүүрэг", "Дэлгүүр", "Зочид буудал", "Ресторан", "Сургууль", "Төрийн байгууллага",
			  "Үзвэр үйлчилгээ", "Үсчин, гоо сайхан", "Үүрэн холбоо", "Цайны газар", "Цэцэрлэг", "Шатахуун түгээх станц", "Эмийн сан", "Эмнэлэг", "Цагдаа", 
			  "Автобус", "Хороо"};
	  private ArrayList<Integer> expanded_group =new ArrayList<Integer>();
	  private NetworkConnectionClass network;
	  	@Override
		public void onBackPressed() {
		   finish();
		   overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
		}
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ub);
		network=new NetworkConnectionClass(this);
		createTempChildData();
		expList_ub = (ExpandableListView)findViewById(R.id.ub_screen_exp);
		expList_ub.setGroupIndicator(null);
		expList_ub.setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				//Child дээр дарахад тухайн child-н ID гаар нь дараагын дэлгэрэнгүйг харах
				Intent intent = new Intent(UBActivity.this, UBViewActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt("title", R.id.title_menu_4);
				bundle.putInt("id", child_ids.get(groupPosition).get(childPosition));
				intent.putExtras(bundle);

				startActivity(intent);
				overridePendingTransition(R.anim.right_in, R.anim.no_anim);
				return false;
			}
		});
		expList_ub.setOnGroupClickListener(new OnGroupClickListener() {
			
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				// TODO Auto-generated method stub
				
				if(!expList_ub.isGroupExpanded(groupPosition))
				{
					boolean isExpandedBefore = false;
					for(int j=0;j<expanded_group.size();j++)
					{
						if(expanded_group.get(j)==groupPosition)
						{
							isExpandedBefore=true;
							break;
						}
							
					}
					if(!isExpandedBefore)
					{
						
						final int g_position = groupPosition;
						final ProgressDialog dialog = ProgressDialog.show(UBActivity.this, null, 
				    			getResources().getString(R.string.dialog_please_wait), true);
				    	
				    			final Handler handler = new Handler() {
				    			   public void handleMessage(Message msg) {
				    				   //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
				    				   if(msg.what==1)
				    				   {
					    				   main_adapter.notifyDataSetChanged();
					    				   expList_ub.expandGroup(g_position);
				    				   }
				    				   else
				    					   Toast.makeText(UBActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();

				    				   dialog.dismiss();
				    			      }
				    			   };
				    			Thread checkUpdate = new Thread() {  
				    			   public void run() {
				    				   //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
				    				   if(network.isConnectedToServer(getResources().getString(R.string.json_ub_exp_data)+String.valueOf(g_position+1), 5000) && network.isNetworkConnected())
				    				   {
				    					   expanded_group.add(g_position);
				    					   JSONfuncObject json_main_data = new JSONfuncObject();

				    					   
				    					   JSONObject json_data = json_main_data.getJSONfromURL(UBActivity.this.getResources().getString(R.string.json_ub_exp_data)+String.valueOf(g_position+1));
				    					   try {
											JSONArray comid_array = json_data.getJSONArray(UBActivity.this.getResources().getString(R.string.json_ub_getcomid));
											JSONArray comname_array = json_data.getJSONArray(UBActivity.this.getResources().getString(R.string.json_ub_getcomname));
											ArrayList<String> child_sub_name = new ArrayList<String>();
											ArrayList<Integer> child_sub_id = new ArrayList<Integer>();
											if(!comname_array.getString(0).equals(""))
											for(int i=0;i<comname_array.length();i++)
											{
												child_sub_id.add(comid_array.getInt(i));
												child_sub_name.add(comname_array.getString(i));
											}
											child_datas.set(g_position, child_sub_name);
											child_ids.set(g_position, child_sub_id);
										} catch (NotFoundException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}  
				    				   
				    				   handler.sendEmptyMessage(1);
				    				   }
				    				   else
				    					   handler.sendEmptyMessage(0);
				    				   
				    			      }
				    			   };
				    			checkUpdate.start();
					}
					
				}
				   
 
					   
				return false;
			}
		});
		createTitleComponents();
		findViewById(R.id.title_menu_4).setBackgroundResource(R.drawable.text_background);
		focusOnView();
		
		createExpData();
	}
	private void createTempChildData()
	{
		for(int i=0;i<ub_parents.length;i++)
		{
			ArrayList<Integer> temp_child_id = new ArrayList<Integer>();
			ArrayList<String> temp_child_data = new ArrayList<String>();
			child_datas.add(temp_child_data);
			child_ids.add(temp_child_id);
		}
	}
	public void createExpData()
	{
		//JSON уншаагүй байгаа болохоор тест маягаар гараас шууд өгөгдөл уншиж байгаа Json уншихад Thread доторхыг солино
		parent_datas.clear();
		//child_datas.clear();
		//child_ids.clear();
		
		final ProgressDialog dialog = ProgressDialog.show(UBActivity.this, null, 
    			getResources().getString(R.string.dialog_please_wait), true);
    	
    			final Handler handler = new Handler() {
    			   public void handleMessage(Message msg) {
    				   //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
    				   main_adapter = new MainExpandableAdapter(UBActivity.this, parent_datas, null, child_datas, null);
    				   expList_ub.setAdapter(main_adapter);
    				   dialog.dismiss();
    			      }
    			   };
    			Thread checkUpdate = new Thread() {  
    			   public void run() {
    				   //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
    				   for(int i=0;i<ub_parents.length;i++)
    				   {
    					   parent_datas.add(ub_parents[i]);
    				   }
    				   handler.sendEmptyMessage(0);
    			      }
    			   };
    			checkUpdate.start();
    			
		
	}
	public void onResume()
	{
		super.onResume();
		focusOnView();
	}
	private final void focusOnView(){
        new Handler().post(new Runnable() {
            @Override
            public void run() {
            	findViewById(R.id.title_scroll_view).scrollTo(findViewById(R.id.title_menu_4).getLeft()-10, 0);
            }
        });
    }
	public void createTitleComponents()
	{
		//Хуудасны дээр байрлах толгой хэсгийн хийх үйлдлүүд
		
		//Үндсэн товчлууруудын үйлдэл
		//Буцах товчлуур
		findViewById(R.id.back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		//Хадгалсан мэдээ унших товчлуур
		findViewById(R.id.title_history).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(UBActivity.this, ItemActivityFromDB.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Хайх товчлуур
		findViewById(R.id.title_search).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(UBActivity.this, SearchActivity.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Тухай товчлуур
		findViewById(R.id.title_info).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(UBActivity.this, InformationActivity.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Home буюу лого дээр дарах үйлдэл
		findViewById(R.id.home).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			}
		});
		
		
		
		//Програмын үндсэн менюны үйлдлүүд
		findViewById(R.id.title_menu_1).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UBActivity.this, MainActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_2).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UBActivity.this, RentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_3).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UBActivity.this, NewApartmentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_4).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				Intent intent = new Intent(UBActivity.this, UBActivity.class); 
//				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
//				startActivity(intent);
			}
		});
		findViewById(R.id.title_menu_5).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UBActivity.this, AutomobileActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
	}
}
